import React, { useEffect, useState } from 'react'
import { Route, Switch, Redirect } from 'react-router-dom'
import routers, { noRootRouters, homeRouters } from '../router'
import { getCookie, searchLeaves } from '../utils/common'
import { connect } from 'react-redux'
import { getTokenInfo } from '../store/user/actionCreators'
import {
  getServiceInfo,
} from '../store/page/actionCreators'
import { showLoad, hideLoad } from '../utils/globalLoading.js'
import { ConfigProvider } from 'antd'
import zhCN from 'antd/es/locale/zh_CN'

const Main = (props) => {
  // console.log('props.history', props.history)
  const {
    history,
    // updateHistoryAction,
    getTokenInfo,
    userState,
    getServiceInfo,
  } = props
  const token = getCookie('token')
  const userInfoExist = Object.keys(userState.user).length > 0
  const [homeRoutes, setHomeRoutes] = useState([])
  useEffect(() => {
    setHomeRoutes(searchLeaves(homeRouters))
    // 存储history
    // updateHistoryAction(history)
    // 检查token
    if (token) {
      console.log('有token')
      // 获取用户信息
      getUserInfo()
      // 获取服务器cms配置
      getCMS()
    } else {
      console.log('没有token')
      // 跳转到login
      history.replace('/login')
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => {
    // const {pathname} = props.history.location
    // if (homeRoutes.length && !homeRoutes.some(item => item.path === pathname) && !['/login', '/notfound', '/'].includes(pathname)) {
    //   // 跳转到404
    //   props.history.replace('/notfound')
    // }
  }, [homeRoutes, props.history, props.history.location])

  const getUserInfo = async () => {
    try {
      showLoad()
      await getTokenInfo()
    } catch (e) {
      // history.replace('/login')
    } finally {
      hideLoad()
    }
  }

  const getCMS = async () => {
    try {
      showLoad()
      await getServiceInfo()
    } catch (e) {
      // history.replace('/login')
    } finally {
      hideLoad()
    }
  }
  return (
    <ConfigProvider locale={zhCN}>
      <Switch>
        <Route path="/" exact render={ () => {
          if (token) {
            return <Redirect to="/main"></Redirect>
          } else {
            return <Redirect to="/login"></Redirect>
          }
        } }></Route>
        {
          noRootRouters.map((item, index) => (
            <Route
              key={index}
              path={item.path}
              exact={item.exact}
              component={item.component}
            ></Route>
          ))
        }
      </Switch>
    </ConfigProvider>
  )
}

const stateToProps = (state, props) => {
  return {
    ...props,
    ...state,
  }
}

const actionToProps = {
  getTokenInfo,
  // updateHistoryAction,
  getServiceInfo,
}

export default connect(stateToProps, actionToProps)(Main)
